package com.north.light.libpicselect.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.north.light.libpicselect.R;
import com.north.light.libpicselect.bean.LibMediaType;
import com.north.light.libpicselect.bean.LibPicInfo;
import com.north.light.libpicselect.utils.LibMediaSelectUtils;
import com.north.light.libpicselect.utils.LibPicCloneUtils;
import com.north.light.libpicselect.utils.LibPicDateUtils;
import com.north.light.libpicselect.utils.LibPicPicScreenUtils;
import com.north.light.libpicselect.utils.LibPicToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * create by lzt
 * data 2019/12/8
 * <p>
 * change by lzt 20200823 增加视频数据源显示适配
 * change by lzt 20210809 修复没有选择图片时，相机图标显示不全问题
 * change by lzt 20220702 增加视频资源，时长显示
 * change by lzt 20220702 增加tag,修改布局。防止图片显示错乱
 */
public class LibPicSelAdapter extends LibPicSelBaseAdapter<LibPicSelAdapter.PicHolder> {
    private Context mContext;
    private List<LibPicInfo> mResult = new ArrayList<>();
    private BindImageViewListener mBindListener;
    private OnClickListener mOnClick;
    private long mScreenWidth;

    private int mSelectLimit = 9;//默认可选9个
    private boolean isShowCamera;//是否显示相机的标识

    private static final Object mLock = new Object();


    public LibPicSelAdapter(Context mContext, boolean isShowCamera) {
        this.mContext = mContext;
        this.isShowCamera = isShowCamera;
        mScreenWidth = LibPicPicScreenUtils.getScreenWidth(mContext);
    }

    public void setSelectLimit(int selectLimit) {
        this.mSelectLimit = selectLimit;
    }

    /**
     * 每次设置数据，都对比一下传入的图片集合
     */
    public void setData(List<LibPicInfo> data) {
        if (data == null) {
            data = new ArrayList<>();
        }
        List<LibPicInfo> result = LibPicCloneUtils.cloneObjectSer(data);
        mResult.clear();
        //需要防止对象引用-------------------------------
        for (LibPicInfo cache : result) {
            LibPicInfo arg = LibPicCloneUtils.cloneObjectSer(cache);
            mResult.add(arg);
        }
        //对比已选择的数据-------------------------------
        if (getParams() != null) {
            List<String> selectList = getParams().getSelPicList();
            int selectCount = selectList.size();
            if (selectCount != 0) {
                for (LibPicInfo local : mResult) {
                    //对比传入的数据
                    for (int i = 0; i < selectList.size(); i++) {
                        if (!TextUtils.isEmpty(local.getPath()) &&
                                local.getPath().equals(selectList.get(i))) {
                            if(!local.getIsSelect().isSel()){
                                local.setSelect(true);
                            }
                        }
                    }
                }
            }
        }
        //设置选中的顺序
        List<LibPicInfo> selPicList = getSelectPicInfo();
        sortItem(selPicList);
        notifyDataSetChanged();
    }

    /**
     * 更新本地选中状态--取消选中的时候需要更新选中集合
     */
    private void updateLocalSel(String path) {
        synchronized (mLock) {
            if (TextUtils.isEmpty(path)) {
                return;
            }
            List<String> trainList = new ArrayList<>();
            if (getParams() != null) {
                List<String> selectList = getParams().getSelPicList();
                if (selectList.size() != 0) {
                    for (String selPic : selectList) {
                        if (!TextUtils.isEmpty(selPic) && !path.equals(selPic)) {
                            trainList.add(selPic);
                        }
                    }
                    //设置参数
                    getParams().setSelPicList(trainList);
                }
            }
        }
    }

    /**
     * 获取选中的数据
     * 遍历选中数据的集合--直接返回
     */
    public List<String> getSelectInfo() {
        List<String> result = new ArrayList<>();
        List<LibPicInfo> cacheList = new ArrayList<>();
        for (LibPicInfo cache : mResult) {
            if (cache.isSelect()) {
                cacheList.add(cache);
            }
        }
        //排序
        Collections.sort(cacheList, new Comparator<LibPicInfo>() {
            @Override
            public int compare(LibPicInfo o1, LibPicInfo o2) {
                return (int) (o1.getSelTime() - o2.getSelTime());
            }
        });
        //转换
        for (LibPicInfo cache : cacheList) {
            if (cache.isSelect()) {
                result.add(cache.getPath());
            }
        }
        return result;
    }

    @NonNull
    @Override
    public PicHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PicHolder(LayoutInflater.from(mContext).inflate(R.layout.lib_pic_item_main_content, parent, false));
    }

    @Override
    public void onViewRecycled(@NonNull PicHolder holder) {
        super.onViewRecycled(holder);
        holder.mCheckBox.setOnCheckedChangeListener(null);
        holder.mImage.setBackground(null);
        holder.mImage.setImageDrawable(null);
    }


    @Override
    public void onBindViewHolder(@NonNull final PicHolder holder, final int itemPos) {
        //设置图片显示通用宽高-----------------
        RelativeLayout.LayoutParams mImgP = (RelativeLayout.LayoutParams) holder.mImage.getLayoutParams();
        mImgP.height = (int) (mScreenWidth / 4);
        holder.mImage.setLayoutParams(mImgP);
        holder.mCoveringLayer.setLayoutParams(mImgP);
        //设置图片显示通用宽高-----------------
        if (isShowCamera && itemPos == 0) {
            holder.mImage.setVisibility(View.GONE);
            holder.mCamera.setVisibility(View.VISIBLE);
            holder.mCheckBox.setVisibility(View.GONE);
            String positionStr = String.valueOf(itemPos);
            holder.mCamera.setTag(R.id.lib_pic_img_id, positionStr);
            if (holder.mCamera.getTag(R.id.lib_pic_img_id) != null &&
                    positionStr == (holder.mCamera.getTag(R.id.lib_pic_img_id))) {
                holder.mCamera.setImageResource(R.drawable.lib_pic_ic_camera_alt_black_24dp);
            }
            holder.mCamera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnClick != null) {
                        mOnClick.camera();
                    }
                }
            });
            holder.mSource.setVisibility(View.GONE);
            holder.mCoveringLayer.setVisibility(View.GONE);
        } else {
            holder.mCamera.setVisibility(View.GONE);
            holder.mImage.setVisibility(View.VISIBLE);
            final int position = isShowCamera ? (itemPos - 1) : itemPos;
            LibPicInfo cacheInfo = mResult.get(position);
            holder.mCheckBox.setVisibility(View.VISIBLE);
            String path = !TextUtils.isEmpty(cacheInfo.getPath()) ? cacheInfo.getPath() : String.valueOf(position);
            holder.mImage.setTag(R.id.lib_pic_img_id, path);
            if (holder.mImage.getTag(R.id.lib_pic_img_id) != null &&
                    path == (holder.mImage.getTag(R.id.lib_pic_img_id))) {
                if (mBindListener != null) {
                    mBindListener.BindImageView(mResult.get(position).getPath(), holder.mImage);
                }
            }

            //是否显示选择顺序逻辑
            boolean showSelectOrder;
            if (getParams() == null) {
                showSelectOrder = false;
            } else {
                showSelectOrder = (cacheInfo.getIsSelect().getIndex() != -1) && getParams().isSelectOrder();
            }
            holder.mSelectOrder.setVisibility((showSelectOrder) ? View.VISIBLE : View.GONE);
            holder.mCoveringLayer.setVisibility((showSelectOrder) ? View.VISIBLE : View.GONE);
            if (showSelectOrder) {
                //需要显示选择顺序
                holder.mSelectOrder.setText(String.valueOf(cacheInfo.getIsSelect().getIndex()));
            }

            //选中状态更新
            holder.mCheckBox.setChecked(cacheInfo.isSelect());
            //数据源判断
            if (cacheInfo.getSource() == LibMediaType.VIDEO.getSource()) {
                //视频源
                long duration = cacheInfo.getDuration();
                String timeDesc = LibPicDateUtils.formatTime(duration);
                holder.mSource.setText(timeDesc);
                holder.mSource.setVisibility(View.VISIBLE);
            } else {
                //非视频资源
                holder.mSource.setVisibility(View.GONE);
            }
            holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        int selectCount = 0;
                        for (LibPicInfo cache : mResult) {
                            if (cache.isSelect()) {
                                selectCount++;
                            }
                        }
                        if (selectCount < mSelectLimit) {
                            //可以选择
                            if (checkCondition(position)) {
                                cacheInfo.setSelect(true);
                                sortItem(getSelectPicInfo());
                            } else {
                                //设置为未选中状态
                                holder.mCheckBox.setChecked(false);
                            }
                        } else {
                            holder.mCheckBox.setChecked(false);
                            //超出了上限
                            if (mOnClick != null) {
                                mOnClick.tipsMaxSel(mSelectLimit);
                            }
                        }
                    } else {
                        //设置选中数据
                        cacheInfo.setSelect(false);
                        notifyItemChanged(itemPos);
                        //更新本地数据
                        updateLocalSel(cacheInfo.getPath());
                        sortItem(getSelectPicInfo());
                    }
                    //回调事件
                    if (mOnClick != null) {
                        mOnClick.check();
                    }
                }
            });
            holder.mImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnClick != null) {
                        //区分点击的是图片还是视频
                        mOnClick.click(mResult, position, mResult.get(position).getSource());
                    }
                }
            });
        }
    }

    /**
     * 区分排序前还是排序后
     */
    private void sortItem(List<LibPicInfo> picList) {
        if (picList == null || picList.size() == 0) {
            return;
        }
        //排序
        Collections.sort(picList, new Comparator<LibPicInfo>() {
            @Override
            public int compare(LibPicInfo o1, LibPicInfo o2) {
                return (int) (o1.getSelTime() - o2.getSelTime());
            }
        });
        for (int i = 0; i < picList.size(); i++) {
            picList.get(i).getIsSelect().setIndex(i + 1);
        }
        notifyDataSetChanged();
    }

    /**
     * 校验选择条件
     */
    private boolean checkCondition(int selPos) {
        if (selPos >= mResult.size()) {
            //越界
            return false;
        }
        List<LibPicInfo> selPicInfo = getSelectPicInfo();
        LibPicInfo clickInfo = mResult.get(selPos);
        return LibMediaSelectUtils.checkCondition(clickInfo, selPicInfo, getParams(), new LibMediaSelectUtils.TipsListener() {
            @Override
            public void message(String tips) {
                LibPicToastUtils.toast(mContext.getApplicationContext(), tips, Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mResult.size() + (isShowCamera ? 1 : 0);
    }

    public List<LibPicInfo> getPicInfo() {
        return mResult;
    }


    public List<LibPicInfo> getSelectPicInfo() {
        List<LibPicInfo> result = new ArrayList<>();
        for (LibPicInfo cache : mResult) {
            if (cache.isSelect()) {
                result.add(cache);
            }
        }
        return result;
    }


    public class PicHolder extends RecyclerView.ViewHolder {
        private ImageView mImage;
        private ImageView mCamera;
        private CheckBox mCheckBox;
        //数据源
        private TextView mSource;

        private TextView mSelectOrder;

        private ImageView mCoveringLayer;

        public PicHolder(@NonNull View itemView) {
            super(itemView);
            mCamera = itemView.findViewById(R.id.lib_pic_item_main_content_camera);
            mImage = itemView.findViewById(R.id.lib_pic_item_main_content_image);
            mCheckBox = itemView.findViewById(R.id.lib_pic_item_main_content_checkbox);
            mSource = itemView.findViewById(R.id.lib_pic_item_main_content_source);
            mSelectOrder = itemView.findViewById(R.id.lib_pic_item_main_content_sel_order);
            mCoveringLayer = itemView.findViewById(R.id.lib_pic_item_main_content_covering_layer);
        }
    }

    //点击事件
    public interface OnClickListener {
        //点击事件__20200823增加数据源入参
        void click(List<LibPicInfo> data, int pos, int source);

        //check box事件
        void check();

        //相机点击事件
        void camera();

        //消息提示---------------
        //最多选择多少个
        void tipsMaxSel(int max);

    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.mOnClick = onClickListener;
    }

    public void removeOnClickListener() {
        this.mOnClick = null;
    }

    //绑定外部图片加载的方法
    public interface BindImageViewListener {
        void BindImageView(String path, ImageView iv);
    }

    public void setOnBindImageViewListener(BindImageViewListener bindListener) {
        this.mBindListener = bindListener;
    }

    public void reomveBindImageViewListener() {
        this.mBindListener = null;
    }
}
